package com.mail.run;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.DefaultHttpParams;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.springframework.stereotype.Component;

@Component
public class CheckMail {
    private final Boolean isProxy = false;

    public CheckMail() {

    }
    public CheckMail(Boolean isProxy) {
        // this.isProxy = isProxy;
    }

    // 设置只是输出错误信息*****************begin*******************
    static {
        System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog");
        System.setProperty("org.apache.commons.logging.simplelog.showdatetime", "true");
        System.setProperty("org.apache.commons.logging" + ".simplelog.log.org.apache.commons.httpclient", "error");
    }

    // 设置只是输出错误信息*****************end*******************
    public Boolean loginEmail(String userName, String userPassword) {
        HttpClient httpClient = new HttpClient();// 定义一个客户端
        String goUrl = "";
        // System.out.println("SendMessagesWithEmail.loginEmail()");
        // 链接超时
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(10000);
        // 读取超时
        httpClient.getHttpConnectionManager().getParams().setSoTimeout(18000);
        if (isProxy) {
            httpClient.getHostConfiguration().setProxy("192.168.1.1", 8080);
            UsernamePasswordCredentials creds = new UsernamePasswordCredentials("test", "test");
            httpClient.getState().setProxyCredentials(AuthScope.ANY, creds);
        }
        // 登陆请求
        PostMethod postMethod = new PostMethod(
                                               "https://mail.126.com/entry/cgi/ntesdoor?&df=mail126_letter&from=web&funcid=loginone&iframe=1&language=-1&passtype=1&product=mail126&verifycookie=-1&net=failed&style=-1&race=-2_-2_-2_db&uid=hemin10822@126.comhid=10010102");// 设置一个post请求
        HttpMethodParams params = postMethod.getParams();
        params.setContentCharset("UTF-8"); // 设置编码
        List<NameValuePair> nameValues = new ArrayList<NameValuePair>();// 设置参数列表
        nameValues.add(new NameValuePair("username", userName));
        nameValues.add(new NameValuePair("password", userPassword));
        nameValues.add(new NameValuePair("savelogin", "yes"));
        nameValues.add(new NameValuePair("url2", "http://mail.126.com/errorpage/err_126.htm"));
        List<Header> headers = new ArrayList<Header>();
        headers.add(new Header("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)"));
        httpClient.getHostConfiguration().getParams().setParameter("http.default-headers", headers);
        postMethod.setRequestBody(nameValues.toArray(new NameValuePair[nameValues.size()]));// 添加参数列表
        // 解决cookie报错信息
        DefaultHttpParams.getDefaultParams().setParameter("http.protocol.cookie-policy",
                                                          CookiePolicy.BROWSER_COMPATIBILITY);
        try {
            httpClient.executeMethod(postMethod);
            String returnBody = postMethod.getResponseBodyAsString();
            // 随时可能变动，可用正确的邮箱登陆后查看串
            String urlPattern = "http://mail.126.com/js6/main.jsp?(.*);";
            Pattern p1 = Pattern.compile(urlPattern);
            Matcher m1 = p1.matcher(returnBody);
            // System.out.println(returnBody);
            return m1.find();
            /*
             * if (m1.find()) {
             * goUrl = m1.group().substring(0, (m1.group().length() - 2));
             * System.out.println("登陆成功");
             * System.out.println("跳转地址是：" + goUrl);
             * GetMethod getMethod = new GetMethod(goUrl);
             * System.out.println("执行跳转地址*******************");
             * httpClient.executeMethod(getMethod);
             * System.out.println(getMethod.getResponseBodyAsString());
             * Cookie[] cookies = httpClient.getState().getCookies();
             * for (Cookie c : cookies) {
             * System.out.println("name：" + c.getName() + "　value:  " + c.getValue());
             * }
             * // 查询发件箱
             * StringBuffer reqXmlBufer = new StringBuffer();
             * reqXmlBufer.append("<?xml version=\"1.0\"?><object>");
             * reqXmlBufer.append("<int name=\"fid\">3</int>");
             * reqXmlBufer.append("<string name=\"order\">date</string>");
             * reqXmlBufer.append("<boolean name=\"desc\">true</boolean>");
             * reqXmlBufer.append("<int name=\"limit\">20</int>");
             * reqXmlBufer.append("<int name=\"start\">0</int>");
             * reqXmlBufer.append("<boolean name=\"skipLockedFolders\">false</boolean>");
             * reqXmlBufer.append("<string name=\"topFlag\">top</string>");
             * reqXmlBufer.append("<boolean name=\"returnTag\">true</boolean>");
             * reqXmlBufer.append("<boolean name=\"returnTotal\">true</boolean></object>");
             * String querySendBoxUrl = "http://mail.126.com/js6/s?sid=" + cookies[17].getValue()
             * + "&func=mbox:listMessages&from=nav&group=folder&id=3&action=click";
             * PostMethod querySendBox = new PostMethod(querySendBoxUrl);
             * querySendBox.setRequestHeader("Content-Type", "text/xml;charset=ISO-8859-1");
             * RequestEntity reqEntity = new StringRequestEntity(reqXmlBufer.toString(), null,
             * null);
             * querySendBox.setRequestEntity(reqEntity);
             * httpClient.executeMethod(querySendBox);
             * System.out.println("sendBox:" + querySendBox.getResponseBodyAsString());
             * // SEND MAIL
             * // sendEmail(httpClient);
             * } else {
             * System.out.println("登陆失败");
             * }
             */
        } catch (HttpException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    private void sendEmail(HttpClient client) throws IOException {
        Cookie[] cookies = client.getState().getCookies();
        StringBuffer sendXml = new StringBuffer();
        sendXml.append("<?xml version=\"1.0\"?>");
        sendXml.append("<object>");
        sendXml.append("<string name=\"id\">c:1401897506026</string>");
        sendXml.append("<object name=\"attrs\">");
        sendXml.append("<string name=\"account\">\"hemin108\"&lt;hemin108@122226.com&gt;</string>");
        sendXml.append("<boolean name=\"showOneRcpt\">true</boolean>");
        sendXml.append("<array name=\"to\"><string>\"303645105\"&lt;303645105@qq.com&gt;</string>");
        sendXml.append("</array><array name=\"cc\"/><array name=\"bcc\"/>");
        sendXml.append("<string name=\"subject\">new test2</string>");
        sendXml.append("<boolean name=\"isHtml\">true</boolean>");
        sendXml.append("<string name=\"content\">tetst</string>");
        sendXml.append("<int name=\"priority\">3</int>");
        sendXml.append("<boolean name=\"saveSentCopy\">true</boolean>");
        sendXml.append("<string name=\"charset\">GBK</string>");
        sendXml.append("</object>");
        sendXml.append("<boolean name=\"returnInfo\">false</boolean>");
        sendXml.append("<string name=\"action\">deliver</string>");
        sendXml.append("</object>");
        System.out.println("17 cooies:" + cookies[17]);
        String sendUrl = "http://mail.126.com/js6/s?sid=" + cookies[17].getValue()
                + "&func=mbox:compose&cl_send=1&l=compose&action=deliver&sign=1";
        PostMethod sendMail = new PostMethod(sendUrl);
        RequestEntity reqXmlEntity = new StringRequestEntity(sendXml.toString(), null, "GBK");
        sendMail.setRequestEntity(reqXmlEntity);
        sendMail.setRequestHeader("Content-Type", "text/xml;charset=GBK");
        client.executeMethod(sendMail);
        Header[] headers = sendMail.getResponseHeaders();
        for (Header h : headers) {
            System.out.println(h.getName() + "  : " + h.getValue());
        }
        System.out.println("state code :" + sendMail.getStatusCode());
        System.out.println("sendBox:" + sendMail.getResponseBodyAsString());
    }

    public static void main(String[] args) {
        new CheckMail(false).loginEmail("hemin108@126.com", "XINXI07110822609");;
    }
}
